package com.xh.one2one.knowledgeSystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xh.one2one.knowledgeSystem.bean.request.KnowledgeTemplateModuleRequest;
import com.xh.one2one.knowledgeSystem.model.KnowledgeTemplateModule;
import com.xh.one2one.knowledgeSystem.dao.KnowledgeTemplateModuleMapper;
import com.xh.one2one.knowledgeSystem.service.IKnowledgeTemplateModuleService;
import com.xh.core.service.impl.BaseServiceImpl;
import org.springframework.stereotype.Service;
import com.xh.core.bean.XhPage;
import com.xh.core.util.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * <p>
 * 知识元模板的模块 服务实现类
 * </p>
 *
 * @author tw
 * @since 2020-12-22
 */
@Service
public class KnowledgeTemplateModuleServiceImpl extends BaseServiceImpl<KnowledgeTemplateModuleMapper, KnowledgeTemplateModule> implements IKnowledgeTemplateModuleService {
    @Override
    public XhPage queryKnowledgeTemplateModulePage(XhPage page, KnowledgeTemplateModuleRequest bean) {
        QueryWrapper qw=new QueryWrapper<KnowledgeTemplateModule>();
        //拼装条件
        qw=prepareParams(bean, qw);

        return (XhPage) this.dao.selectPage(page,qw);
    }

    @Override
    public List queryKnowledgeTemplateModule(KnowledgeTemplateModuleRequest bean) {
        QueryWrapper qw=new QueryWrapper<KnowledgeTemplateModule>();
        //拼装条件
        qw=prepareParams(bean, qw);

        if(!StringUtils.isEmpty(bean.getId())){
            qw.eq("id",bean.getId());
        }

        if(!StringUtils.isEmpty(bean.getPid())){
            qw.eq("pid",bean.getPid());
        }

        qw.orderByAsc("sort");
        return this.dao.selectList(qw);
    }


    @Override
    public void sortKnowledgeTemplateModule(KnowledgeTemplateModule bean) {
        QueryWrapper qw=new QueryWrapper<KnowledgeTemplateModule>();

        qw.eq("pid",bean.getPid());
        qw.ge("sort",bean.getSort());
        qw.orderByAsc("sort");
        List<KnowledgeTemplateModule> list = this.dao.selectList(qw);
        if(!CollectionUtils.isEmpty(list)){
            for (int i = 0; i < list.size(); i++) {
                list.get(i).setSort(bean.getSort() + i + 1);
                dao.updateById(list.get(i));
            }
        }

    }


    /**
     * 准备条件
     * @param bean
     * @param qw
     */
    private QueryWrapper prepareParams(KnowledgeTemplateModuleRequest bean, QueryWrapper qw) {
        if(bean.getIds()!=null&&bean.getIds().length>0){
            qw.in("id",bean.getIds());
        }
        return qw;
    }
}
